<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- Alert 警告 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="handleClick"
        >
          <!-- 基本信息栏 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!--  style="margin-left: 10px;" -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="cateChanged"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数栏 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片栏 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- 图片预览对话框 -->
            <el-dialog title="图片预览" :visible.sync="imgDialogVisible" width="50%">
              <img :src="imgUrl" class="imgStyle">
            </el-dialog>
          </el-tab-pane>
          <!-- 商品内容栏 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"/>
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data() {
    return {
      //存储当前标签页的切换的索引值，与每一个tab-pane的name值对应
      activeIndex: '0',
      //存储基本信息标签中所有表单数据的属性值
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        //存储富文本编辑器的内容
        goods_introduce: '',
        //存储动态参数和静态属性的数据
        attrs: []
      },
      //存储基本信息标签中所有表单数据的校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      //级联选择器下拉菜单数据
      cateList: [],
      //存储级联选择器的配置属性
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      //存储动态参数数据
      manyTableData: [],
      //存储静态属性数据
      onlyTableData: [],
      //存储上传地址
      uploadUrl: 'http://www.ysqorz.top:8888/api/private/v1/upload',
      //请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //设置图片预览对话框的显示与隐藏
      imgDialogVisible: false,
      //图片的url地址
      imgUrl: '',
      //存储富文本框的数据
      editorContent: ''
    }
  },
  created() {
    this.getCatesList()
  },
  methods: {
    //获取级联选择框中分类的数据
    async getCatesList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类失败！')

      this.cateList = res.data
      //   console.log(this.cateList);
    },
    //当选定级联选择器的选项时触发获取参数数据
    cateChanged() {
      /* this.getParamsDate() */
      // console.log(this.cateList);
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat.length = []
        return
      }
    },
    //实现切换标签页时，需要选择好了基本信息中的商品分类一栏
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类！')
        return false
      }
    },
    //切换标签页时获取参数数据（如果不切换，addForm里面不能获取到当前选中分类的参数和属性数据）
    async handleClick() {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.getParamId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取参数数据失败！')
        //获取到的动态参数的数据，将其中的attr_vals进行遍历，如果item存在的话，去掉其中的空格字符，如果不存在，以空数组的形式存储
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTableData = res.data
        this.$message.success('获取参数数据成功！')
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.getParamId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('获取属性数据失败！')
        this.onlyTableData = res.data
        this.$message.success('获取属性数据成功！')
      }
    },
    //点击图片栏的图片触发
    handlePreview(file) {
      console.log(file)
      this.imgUrl = 'http://www.ysqorz.top:8888/' + file.response.data.tmp_path
      this.imgDialogVisible = true
    },
    //删除图片栏图片触发
    handleRemove(file) {
      //1.获取将要删除的图片的临时路径
      const removeFile = file.response.data.tmp_path
      //2.从pics数组中，找到这个图片对应的索引值
      const removeIndex = this.addForm.pics.findIndex(x => x.pic === removeFile)
      console.log('要删除的索引值', removeIndex)
      //3.调用数组的splice方法，把图片信息对象，从pics数组中移除
      this.addForm.pics.splice(removeIndex, 1)
      console.log(this.addForm)
    },
    //当图片上传成功时触发
    handleSuccess(response) {
      //1.将上传成功的图片临时地址存在一个对象中
      const picObj = { pic: response.data.tmp_path }
      //2.将存好的对象push到addForm中
      this.addForm.pics.push(picObj)
      console.log(this.addForm)
    },
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('请填写完整的基本信息！')
        }
        //深拷贝addForm的数据
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        //对动态参数和静态属性里面的数据进行遍历，将其中的attr_id和attr_vals以对象属性的状态赋值给newInfo对象，然后将newInfo添加到addForm里面成为其属性之一
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        console.log(form)
        //提交数据
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201)
          return this.$message.error('添加商品失败！')
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    //获取当前基本信息的商品分类一栏选中的分类的id值
    getParamId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      } else {
        return null
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.imgStyle {
  width: 100%;
}
.addBtn {
  margin-top: 15px;
}
</style>
